import {SimpleFunction} from "plain-design-composition";
import {Page, Tab} from "plain-micro-application";

type EventListener = SimpleFunction & { fn?: SimpleFunction }

type EventObject = {
    pageId: string,                     // 监听事件所在的page的id（page销毁之后自动注销page中所监听的事件）
    tabFirstPageId: string,             // 监听事件所在tab的第一个page的id（tab销毁之后，自动注销tab中所监听的事件，tab的key得改成第一个page的id）
    listener: EventListener,            // 监听事件回调函数
    event: string,                      // 监听的事件名称
}

export const NavigatorEventHandler = (() => {
    let list: EventObject[] = []
    const $on = (event: string, listener: EventListener, tab: Tab, page: Page) => list.push({tabFirstPageId: tab.pages[0].id, pageId: page.id, listener, event,})
    const $once = (event: string, listener: EventListener, tab: Tab, page: Page) => {
        console.log('once', {
            event,
            tabFirstPageId: tab.pages[0].id,
        })
        list.push({
            tabFirstPageId: tab.pages[0].id,
            pageId: page.id,
            event,
            listener: Object.assign((...args: any[]) => {
                listener(...args)
                $off(event, listener, tab, page)
            }, {fn: listener}),
        })
    }
    const $emit = (event: string, data: any[], tab?: Tab) => {
        const emitter = !!tab ? list.filter(i => i.tabFirstPageId === tab.pages[0].id) : list
        emitter.forEach(i => i.listener(...data))
    }
    const $off = (event: string, listener: EventListener, tab: Tab, page: Page) => {
        const index = list.findIndex(i => i.tabFirstPageId === tab.pages[0].id && i.pageId === page.id && i.event === event && (listener === i.listener || listener === i.listener.fn))
        if (index > -1) {list.splice(index, 1)}
    }
    const onBeforeUnmount = {
        page: (page: Page) => {list = list.filter(i => i.pageId !== page.id)},
        tab: (tab: Tab) => {list = list.filter(i => i.tabFirstPageId !== tab.pages[0].id)},
    }
    return {$on, $off, $once, $emit, onBeforeUnmount}
})();